<?php

/**
 * @author Martin Pernica
 * @copyright 2009
 */
class com_content
{
    public static $name = 'content/';
    public static $offset;

    public static $title;

    public $seoParser;
    public $log;

    public $meta;

    public function __construct()
    {
        $this->seoParser = new SeoUrl();
    }

    public function html_strlen($str)
    {
        $chars = preg_split('/(&[^;\s]+;)|/', $str, -1, PREG_SPLIT_NO_EMPTY |
            PREG_SPLIT_DELIM_CAPTURE);
        return count($chars);
    }

    public function printMeta($readmore = true, $cat_id, $comments, $seo_url = '', $hits =
        array(false), $id = 0)
    {
        if ($hits[0]) {
            $hits[1] = $hits[1];
        } else {
            $hits[1] = '';
        }

        $sec_id = DbModel::select('categories', 'section', array('id' => intval($cat_id)));
        $sec_id = $sec_id[0][0];

        $this->meta['readmore'] = Lang::getFront('com_content', 'readmore');
        $this->meta['readmore-link'] = $GLOBALS['url'] . 'index.php?q=' . self::$name .
            $seo_url;
        $this->meta['category'] = Lang::getFront('com_content', 'category');
        $this->meta['category-name'] = getCategoryName($cat_id);
        $this->meta['category-link'] = $GLOBALS['url'] . "index.php?q=" . self::$name .
            "categories/" . $cat_id;
        $this->meta['section'] = Lang::getFront('com_content', 'section');
        $this->meta['section-name'] = getSectionName($sec_id);
        $this->meta['section-link'] = $GLOBALS['url'] . "index.php?q=" . self::$name .
            "sections/" . $sec_id;
        $this->meta['comments'] = Lang::getFront('com_content', 'comments');
        $this->meta['comments-link'] = $GLOBALS['url'] . "index.php?q=" . self::$name .
            $seo_url . "#comments";
        $this->meta['comments-count'] = $comments;
        $this->meta['hits'] = $hits[1];
        $this->meta['print'] = Lang::getFront('com_content', 'print');
        $this->meta['print-link'] = $GLOBALS['url'] . "index.php?q=print/" . $id;

    }

    public static function printNavigation($p = 'content', $rowsPerPage)
    {
        $q = Registry::get('q');
        $query = Registry::get('db')->query("SELECT SQL_CALC_FOUND_ROWS id FROM {prefix}articles WHERE published = '1'");
        $query = Registry::get('db')->query("SELECT FOUND_ROWS() AS numrows");
        $row = $query->fetch_array();
        $numrows = $row['numrows'];
        $pageNum = (empty($q[1]) ? '1' : intval($q[1]));

        $maxPage = ceil($numrows / $rowsPerPage);
        $self = $_SERVER['PHP_SELF'];
        $nav = '';

        for ($page = 1; $page <= $maxPage; $page++) {
            if ($page == $pageNum) {
                $nav .= "<a href=\"#\">" . $page . "</a>";
            } else {
                $nav .= " <a href=\"" . $self . "?q=" . $p . "/page/" . $page . "\">" . $page .
                    "</a> ";
            }
        }
        if ($pageNum > 1) {
            $page = $pageNum - 1;
            $prev = " <a href=\"{url}content/page/" . $page . "\">‹</a> ";

            $first = " <a href=\"{url}content/page/1\">«</a> ";
        } else {
            $prev = '&nbsp;';
            $first = '&nbsp;';
        }

        if ($pageNum < $maxPage) {
            $page = $pageNum + 1;
            $next = " <a href=\"{url}content/page/" . $page . "\">›</a> ";

            $last = " <a href=\"{url}content/page/" . $maxPage . "\">»</a> ";
        } else {
            $next = '&nbsp;';
            $last = '&nbsp;';
        }

        echo '<div class="pagenav" >' . $first . $prev . $nav . $next . $last . '</div>';

    }

    public function getAllArticles($offset, $rowsPerPage)
    {

        $query = Registry::get('db')->query("SELECT date, author_id, title, id, pretext, cat_id, hits FROM {prefix}articles WHERE published = '1' AND frontpage = '1' ORDER BY notice DESC, date DESC LIMIT " .
            $offset . "," . $rowsPerPage);

        while ($data = $query->fetch_object()) {
            $tlp = Content::parseTlp("com_content", "allArticles.phtml");
            $author = User::getDisplayName($data->author_id);
            $this->seoParser->Parse($data->title);
            $seo_url = $data->id . "-" . $this->seoParser->result;

            $count_comment = Registry::get('db')->query("SELECT COUNT(id) FROM {prefix}comments WHERE component = 'com_content' AND cid = '" .
                $data->id . "'");
            $count_comment = $count_comment->fetch_array();
            $hits[0] = true;
            $hits[1] = $data->hits;

            $this->printMeta(true, $data->cat_id, $count_comment[0], $seo_url, $hits, $data->
                id);
            $tlp = str_replace("{title}", $data->title, $tlp);
            $tlp = str_replace("{title-link}", $GLOBALS['url'] . "index.php?q=" . self::$name .
                $seo_url, $tlp);
            $tlp = str_replace("{author}", $author, $tlp);
            $tlp = str_replace("{author-link}", $GLOBALS['url'] . "index.php?q=user/single/" .
                $data->author_id, $tlp);
            $tlp = str_replace("{date}", $data->date, $tlp);
            $tlp = str_replace("{pretext}", $data->pretext, $tlp);
            $tlp = str_replace("{readmore}", $this->meta['readmore'], $tlp);
            $tlp = str_replace("{readmore-link}", $this->meta['readmore-link'], $tlp);
            $tlp = str_replace("{category}", $this->meta['category'], $tlp);
            $tlp = str_replace("{category-name}", $this->meta['category-name'], $tlp);
            $tlp = str_replace("{category-link}", $this->meta['category-link'], $tlp);
            $tlp = str_replace("{section}", $this->meta['section'], $tlp);
            $tlp = str_replace("{section-name}", $this->meta['section-name'], $tlp);
            $tlp = str_replace("{section-link}", $this->meta['section-link'], $tlp);
            $tlp = str_replace("{comments}", $this->meta['comments'], $tlp);
            $tlp = str_replace("{comments-link}", $this->meta['comments-link'], $tlp);
            $tlp = str_replace("{comments-count}", $this->meta['comments-count'], $tlp);
            $tlp = str_replace("{hits}", $this->meta['hits'], $tlp);
            $tlp = str_replace("{print}", $this->meta['print'], $tlp);
            $tlp = str_replace("{print-link}", $this->meta['print-link'], $tlp);

            echo $tlp;

            unset($tlp);
            unset($data);
        }
        self::printNavigation('content', $rowsPerPage);

    }

    public function getSingleArticle($id)
    {
        $tlp = Content::parseTlp("com_content", "singleArticle.phtml");

        $id = explode('-', $id);
        $query = Registry::get('db')->query("SELECT date ,author_id, title, id, pretext, text, cat_id, closed, hits FROM {prefix}articles WHERE id = '" .
            $id[0] . "' AND published = '1' LIMIT 1");
        if ((int)$query->num_rows == 0) {
            Text::h2(Lang::getFront('com_content', 'notfound'));
        } else {
            $data = $query->fetch_object();
            Page::setTitle($data->title);
            $hits = Registry::get('db')->query("UPDATE {prefix}articles SET hits = '" .
                intval($data->hits + 1) . "' WHERE id = '" . intval($id[0]) . "'");

            $author = User::getDisplayName($data->author_id);

            $this->seoParser->Parse($data->title);

            $seo_url = $data->id . "-" . $this->seoParser->result;

            $count_comment = Registry::get('db')->query("SELECT COUNT(id) FROM {prefix}comments WHERE component = 'com_content' AND cid = '" .
                $data->id . "'");
            $count_comment = $count_comment->fetch_array();
            $hits = array(true, $data->hits);
            $this->printMeta(false, $data->cat_id, $count_comment[0], $seo_url, $hits,
                intval($id[0]));

            $tlp = str_replace("{title}", $data->title, $tlp);
            $tlp = str_replace("{title-link}", $GLOBALS['url'] . "index.php?q=" . self::$name .
                $seo_url, $tlp);
            $tlp = str_replace("{author}", $author, $tlp);
            $tlp = str_replace("{author-link}", $GLOBALS['url'] . "index.php?q=user/single/" .
                $data->author_id, $tlp);
            $tlp = str_replace("{date}", $data->date, $tlp);
            $tlp = str_replace("{pretext}", $data->pretext, $tlp);
            $tlp = str_replace("{text}", $data->text, $tlp);
            $tlp = str_replace("{readmore}", $this->meta['readmore'], $tlp);
            $tlp = str_replace("{readmore-link}", $this->meta['readmore-link'], $tlp);
            $tlp = str_replace("{category}", $this->meta['category'], $tlp);
            $tlp = str_replace("{category-name}", $this->meta['category-name'], $tlp);
            $tlp = str_replace("{category-link}", $this->meta['category-link'], $tlp);
            $tlp = str_replace("{section}", $this->meta['section'], $tlp);
            $tlp = str_replace("{section-name}", $this->meta['section-name'], $tlp);
            $tlp = str_replace("{section-link}", $this->meta['section-link'], $tlp);
            $tlp = str_replace("{comments}", $this->meta['comments'], $tlp);
            $tlp = str_replace("{comments-link}", $this->meta['comments-link'], $tlp);
            $tlp = str_replace("{comments-count}", $this->meta['comments-count'], $tlp);
            $tlp = str_replace("{hits}", $this->meta['hits'], $tlp);
            $tlp = str_replace("{print}", $this->meta['print'], $tlp);
            $tlp = str_replace("{print-link}", $this->meta['print-link'], $tlp);

            echo $tlp;
            
            if ($data->closed) {
                define('COM_COMMENT_CLOSED', true);
            } else {
                define('COM_COMMENT_CLOSED', false);
            }
            $q = explode('/', $_GET['q']);
            $log = $this->log;

            $cid = explode('-', $q[1]);

            define('COM_COMMENT_BOOT', true);
            define('COM_COMMENT_COMPONENT', 'com_content');
            define('COM_COMMENT_CID', $cid[0]);

            require ('./components/com_comment/com_comment.php');

        }
    }

    public function getListOfCategories()
    {
        Page::setTitle(Lang::getFront('com_content', 'category'));
        echo '<ul>';
        $query = Registry::get('db')->query("SELECT * FROM {prefix}categories");
        while ($data = $query->fetch_object()) {
            $count = Registry::get('db')->query("SELECT COUNT(id) FROM {prefix}articles WHERE cat_id = '" .
                $data->id . "' AND published = '1' ");
            $count = $count->fetch_array();
            echo '<li><a href="{url}index.php?q=' . self::$name . '/categories/' . $data->
                id . '">' . $data->name . ' (' . $count[0] . ')</a></li>';
            echo '<li>    <em>' . $data->description . '</em></li><br />';
        }
        echo '</ul>';

    }

    public function getListOfSections()
    {
        Page::setTitle(Lang::getFront('com_content', 'section'));
        echo '<ul>';
        $query = Registry::get('db')->query("SELECT * FROM {prefix}sections");
        while ($data = $query->fetch_object()) {
            $count = Registry::get('db')->query("SELECT COUNT(id) FROM {prefix}categories WHERE section = '" .
                $data->id . "' ");
            $count = $count->fetch_array();
            echo '<li><a href="{url}index.php?q=' . self::$name . 'sections/' . $data->id .
                '">' . $data->name . ' (' . $count[0] . ')</a></li>';
            echo '<li>    <em>' . $data->description . '</em></li><br />';
        }
        echo '</ul>';

    }

    public function getArticlesFromCategory($cat_id, $limit)
    {
        $query = Registry::get('db')->query("SELECT * FROM {prefix}articles WHERE cat_id = '" .
            intval($cat_id) . "' AND published = '1' ORDER BY date DESC LIMIT " . $limit);
        Page::setTitle(getCategoryName($cat_id));
        echo '<h2>' . Lang::getFront('com_content', 'category') . ' : <em>' .
            getCategoryName($cat_id) . '</em></h2><br />';
        if ((int)$query->num_rows == 0) {
            echo '<h2>' . Lang::getFront('com_content', 'category_empty') . '</h2><ul>';
        } else {
            while ($data = $query->fetch_object()) {
                $author = getUserDataFromDB($data->author_id);
                $this->seoParser->Parse($data->title);
                $seo_url = $data->id . "-" . $this->seoParser->result;

                echo "<li><a href=\"{url}index.php?q=" . self::$name . $seo_url . "\">" . $data->
                    title . "</a></li>";
            }
            echo '</ul>';
        }
    }

    public function getCategoriesFromSection($sec_id, $limit)
    {
        $query = Registry::get('db')->query("SELECT * FROM {prefix}categories WHERE section = '" .
            intval($sec_id) . "' LIMIT " . $limit);
        Page::setTitle(getSectionName($sec_id));
        echo '<h2>' . Lang::getFront('com_content', 'section') . ' : <em>' .
            getSectionName($sec_id) . '</em></h2><br />';
        if ((int)$query->num_rows == 0) {
            echo '<h2>' . Lang::getFront('com_content', 'section_empty') . '</h2><ul>';
        } else {
            while ($data = $query->fetch_object()) {

                echo "<li><a href=\"{url}index.php?q=" . self::$name . "categories/" . $data->
                    id . "\">" . $data->name . "</a></li>";
            }
            echo '</ul>';
        }
    }

}

?>